<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Categories extends Base {
	protected $types = array(
		'0' => 'Default',
		'1' => 'News',
		'2' => 'Recruitment'
	);

	// construct
	public function run() {
		// set permissions
		$this->permissions();

		// manage uri paths
		if(count($this->uri) > 0) {
			@list($func, $id) = $this->uri;
			$this->$func($id ? $id : '0-null');
		} else $this->index();
	}

	// permissions
	private function permissions() {
		// not logged in? don't bother
		if(!isset($this->session->auth))
			die(new Error());

		// no root access?
		if(!(isset($this->session->auth['permissions']['root']) && $this->session->auth['permissions']['root'] == 1))
			die(new Error());
	}

	// category management (root needed)
	public function index() {
		$this->view->func = 'index';

		// set title
		$this->view->title = $this->settings['blizz_guild'] . ' - Console / Categories';

		// query
		$result = $this->db->query("SELECT id, name, description, type FROM categories ORDER BY position");

		// transform
		$data = array();
		while($res = $result->fetchArray(SQLITE3_ASSOC)) {
			$data[] = array(
				'id' => $res['id'],
				'name' => $res['name'],
				'description' => $res['description'],
				'type' => $this->types[$res['type']],
				'link' => $res['id'] . '-' . Helper::generate_named_id($res['name']),
			);
		}

		// output data
		$this->view->data = $data;

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// create new category
	public function create($id) {
		$this->view->func = 'create';

		// send category to view
		$this->view->category = array(
			'id' => 0,
			'name' => 'New Category',
			'type' => 0
		);

		// set title
		$this->view->title = $this->settings['blizz_guild'] . ' - Cosnole / Categories / ' . $this->view->category['name'];

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// edit a category
	public function edit($id) {
		$this->view->func = 'edit';

		// prepare vars
		$id = explode("-", $id, 2);
		$id = $this->db->escapeString((int)reset($id));

		// get category
		$category = $this->db->querySingle("SELECT id, name, description, type FROM categories WHERE id = '{$id}'", true);
		if(!$category)
			die(new Error());

		// set title
		$this->view->title = $this->settings['blizz_guild'] . ' - Console / Categories / ' . $category['name'];

		// send category to view
		$this->view->category = $category;

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// the save function
	public function save() {
		// get vars
		$token = $this->request->post('token', 'int');
		$name = $this->request->post('name');
		$type = $this->request->post('type', 'int');
		$description = $this->request->post('description');
		if(is_null($token) || is_null($name) || is_null($type) || is_null($description))
			return $this->json = array('success' => false);

		// prepare vars
		$token = $this->db->escapeString($token);
		$name = $this->db->escapeString($name);
		$type = $this->db->escapeString($type);
		$description = $this->db->escapeString($description);

		// insert
		if($token == 0) {
			// increment last position
			$position = $this->db->querySingle("SELECT position FROM categories ORDER BY position DESC");
			$position++;

			// insert new category
			$this->db->exec("INSERT INTO categories (name, type, description, position)
				VALUES ('{$name}', '{$type}', '{$description}', '{$position}')");

		// update
		} else $this->db->exec("UPDATE categories SET name='{$name}', type ='{$type}', description ='{$description}' WHERE id = '{$token}'");

		// return success
		return $this->json = array('success' => true);
	}

	// sort categories position
	public function sort() {
		// get vars
		$order = $this->request->post('order', 'array');
		if(is_null($order))
			return $this->json = array('success' => false);

		// start with index 1
		array_unshift($order, 0);
		unset($order[0]);

		// build transactions
		$t = null;
		foreach($order as $position => $id)
			$t .= "UPDATE categories SET position='{$position}' WHERE id = '{$id}';";

		// run transactions
		if(!is_null($t)) $this->db->exec("BEGIN TRANSACTION;" . $t . "COMMIT;");

		// return success
		return $this->json = array('success' => true);
	}

	// delete a category
	public function delete() {
		// get vars
		$id = $this->request->post('id', 'int');
		if(is_null($id))
			return $this->json = array('success' => false);

		// prepare vars
		$id = $this->db->escapeString($id);

		// delete replies
		$this->db->exec("DELETE FROM replies WHERE topic IN (
			SELECT id FROM topics WHERE category = '{$id}'
		)");

		// delete topics
		$this->db->exec("DELETE FROM topics WHERE category = '{$id}'");

		// delete category
		$this->db->exec("DELETE FROM categories WHERE id = '{$id}'");

		// return success + affected rows
		return $this->json = array('success' => true);
	}
}